﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaterFFloatCtrl : MonoBehaviour {

    private GameObject waveGroupsGameObj;
    private Groups waveGroups;
    public float downDetal;

    private float lastAngle;
    private bool hasRecAngle = false;

    public bool isFloat = true;

    void Awake()
    {
        waveGroupsGameObj = GameObject.Find("GameGroup");
        waveGroups = waveGroupsGameObj.GetComponent<Groups>();
    }

	void FixedUpdate () {
        if (isFloat)
        {
            //Debug.Log("x:"+ transform.position.x + "y:" + waveGroups.getY(transform.position.x));
            //Debug.Log("xy: "+waveGroups.getXY(transform.position.x));
            if (waveGroups.getY(transform.position.x) <= -1000f)
            {
            }
            else
            {
                //Debug.Log("DownDetal: " + downDetal);
                transform.position = new Vector3(transform.position.x, waveGroups.getY(transform.position.x)  + 0.3f - downDetal, transform.position.z);

                float y1 = waveGroups.getY(transform.position.x)  + 0.3f;
                float y2 = waveGroups.getY(transform.position.x + 0.0003f)  + 0.3f;

                //Debug.Log("x1:" + transform.position.x + " y1:" + y1);
                //Debug.Log("x2:" + transform.position.x + 0.5f + " y2:" + y2);

                Vector2 cut = new Vector2(transform.position.x + 0.0003f - transform.position.x, y2 - y1);

                float ang = Vector2.Angle(Vector2.up, cut);

                //Debug.Log("angle: " + ang);

                float resAng;
                if (ang > 90)
                {
                    resAng = ang - 90;
                    if (Mathf.Abs(lastAngle - resAng) < 30)
                    {
                        transform.rotation = Quaternion.Euler(0, 0, -resAng);
                    }
                    //Debug.Log("resAngle: " + resAng);
                }
                else
                {
                    resAng = 90 - ang;
                    if (Mathf.Abs(lastAngle - resAng) < 30)
                    {
                        transform.rotation = Quaternion.Euler(0, 0, resAng);
                    }
                    //Debug.Log("resAngle: " + resAng);
                }
                if (!hasRecAngle)
                {
                    hasRecAngle = true;
                    lastAngle = resAng;
                }
            }
        }
    }
}
